package OpenCodes.UI;

import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;

import javax.swing.JPanel;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.JFrame;

import javax.swing.JTabbedPane;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import java.awt.GridBagConstraints;
import javax.swing.JTextField;
import javax.swing.BorderFactory;
import java.awt.Color;
import java.awt.event.ActionEvent;

import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.table.AbstractTableModel;

import OpenCodes.Dominio.Persona;
import OpenCodes.Servicios.Persona.IListadoPersonaServicio;
import OpenCodes.Servicios.Persona.PersonaServicio;
import OpenCodes.Servicios.Persona.IAltaPersonaServicio;
import OpenCodes.Servicios.ServicioException;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class VisualUI extends JFrame implements IUsuarioInterfazPersona {

	private static final long serialVersionUID = 1L;
	private JPanel jContentPane = null;
	private JTabbedPane jTabbedPane = null;
	private JPanel jPanelCarga = null;
	private JPanel jPanelDatos = null;
	private JPanel jPanelComandos = null;
	private JButton botonLimpiar = null;
	private JButton botonCargar = null;
	private JPanel jPanelPersona = null;
	private JPanel jPanelDireccion = null;
	private JLabel jLabel = null;
	private JLabel jLabel1 = null;
	private JLabel jLabel2 = null;
	private JLabel jLabel3 = null;
	private JTextField tfNombre = null;
	private JTextField tfId = null;
	private JTextField tfApellido = null;
	private JTextField tfTelefono = null;
	private JLabel jLabelCalle = null;
	private JLabel jLabelNumero = null;
	private JLabel jLabelPiso = null;
    private JLabel jLabelDepartamento = null;
	private JTextField tfCalle = null;
	private JTextField tfNumero = null;
	private JTextField tfPiso = null;
    private JTextField tfDepartamento = null;
	private List<Persona> listaPersonas;  //  @jve:decl-index=0:
	private IAltaPersonaServicio altaService;  //  @jve:decl-index=0:
	private IListadoPersonaServicio listadoService;  //  @jve:decl-index=0:
	private JPanel jPanelListado = null;
	private JScrollPane jScrollPane = null;
	private JTable jTable = null;

    @Override
	public int getId() {
		return Integer.valueOf(getTfId().getText());
	}

	@Override
	public String getNombre() {
		return getTfNombre().getText();
	}

	@Override
	public String getApellido() {
		return getTfApellido().getText();
	}

      @Override
    public String getTelefono() {
		return getTfTelefono().getText();
	}

	@Override
	public String getCalle() {
		return getTfCalle().getText();
    }

    @Override
    public int getNumero() {
		return Integer.valueOf(getTfNumero().getText());
	}

    @Override
    public String getPiso() {
		return getTfPiso().getText();
	}

    @Override
	public String getDepartamento() {
		return getTfDepartamento().getText();
	}

	@Override
	public void setListaPersonas(List<Persona> lista) {
		this.listaPersonas = lista;
	}

	/**
	 * This method initializes jTabbedPane
	 * 
	 * @return javax.swing.JTabbedPane
	 */
	private JTabbedPane getJTabbedPane() {
		if (jTabbedPane == null) {
			jTabbedPane = new JTabbedPane();
			jTabbedPane.addTab("Carga", null, getJPanelCarga(), null);
			jTabbedPane.addTab("Listado", null, getJPanelListado(), null);
			jTabbedPane.addChangeListener(new javax.swing.event.ChangeListener() {
				public void stateChanged(javax.swing.event.ChangeEvent e) {
					accionCambiarTab(e);
				}
			});	
		}
		return jTabbedPane;
	}

	private void accionCambiarTab(ChangeEvent e) {
		int selTab = getJTabbedPane().getSelectedIndex();
		if (selTab == 1) {
			llenarTablaPersonas();
		}
	}

	private void llenarTablaPersonas() {
		try {
			listadoService.listar(this);
			getJTable().setModel(new PersonasModel(this.listaPersonas));
		} catch (ServicioException e) {
			JOptionPane.showMessageDialog(this, e.getMessage(),
					"Carga de personas", JOptionPane.ERROR_MESSAGE);
		}
	}

	/**
	 * This method initializes jPanelPersona
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJPanelCarga() {
		if (jPanelCarga == null) {
			jPanelCarga = new JPanel();
			jPanelCarga.setLayout(new BorderLayout());
			jPanelCarga.add(getJPanelDatos(), BorderLayout.CENTER);
			jPanelCarga.add(getJPanelComandos(), BorderLayout.SOUTH);
		}
		return jPanelCarga;
	}

	/**
	 * This method initializes jPanelDatos
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJPanelDatos() {
		if (jPanelDatos == null) {
			jPanelDatos = new JPanel();
			jPanelDatos.setLayout(new GridLayout(2, 1));
			jPanelDatos.add(getJPanelPersona());
			jPanelDatos.add(getJPanelDireccion());
		}
		return jPanelDatos;
	}

	/**
	 * This method initializes jPanelComandos
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJPanelComandos() {
		if (jPanelComandos == null) {
			jPanelComandos = new JPanel();
			jPanelComandos.setLayout(new FlowLayout());
			jPanelComandos.add(getBotonLimpiar(), null);
			jPanelComandos.add(getBotonCargar(), null);
		}
		return jPanelComandos;
	}

	/**
	 * This method initializes botonLimpiar
	 * 
	 * @return javax.swing.JButton
	 */
	private JButton getBotonLimpiar() {
		if (botonLimpiar == null) {
			botonLimpiar = new JButton("Limpiar");
			botonLimpiar.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					accionLimpiar(e);
				}
			});
		}
		return botonLimpiar;
	}

	private void accionLimpiar(ActionEvent e) {
		getTfId().setText(null);
		getTfNombre().setText(null);
		getTfApellido().setText(null);
		getTfTelefono().setText(null);
		getTfCalle().setText(null);
		getTfNumero().setText(null);
		getTfPiso().setText(null);
	}

	/**
	 * This method initializes botonCargar
	 * 
	 * @return javax.swing.JButton
	 */
	private JButton getBotonCargar() {
		if (botonCargar == null) {
			botonCargar = new JButton("Cargar");
			botonCargar.addActionListener(new java.awt.event.ActionListener() {
                @Override
				public void actionPerformed(java.awt.event.ActionEvent e) {
					accionCargar(e);
				}
			});
		}
		return botonCargar;
	}

	private void accionCargar(ActionEvent e) {
		try {
			altaService.agregar(this);
			JOptionPane.showMessageDialog(this, "Ingreso exitoso",
					"Carga de personas", JOptionPane.INFORMATION_MESSAGE);
			accionLimpiar(null);
		} catch (ServicioException e1) {
			JOptionPane.showMessageDialog(this, e1.getMessage(),
					"Carga de personas", JOptionPane.ERROR_MESSAGE);
		}
	}

	/**
	 * This method initializes jPanel1
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJPanelPersona() {
		if (jPanelPersona == null) {
			GridBagConstraints gridBagConstraints11 = new GridBagConstraints();
			gridBagConstraints11.anchor = GridBagConstraints.EAST;
			gridBagConstraints11.ipady = 2;
			gridBagConstraints11.ipadx = 2;
			GridBagConstraints gridBagConstraints6 = new GridBagConstraints();
			gridBagConstraints6.fill = GridBagConstraints.BOTH;
			gridBagConstraints6.gridy = 3;
			gridBagConstraints6.weightx = 1.0;
			gridBagConstraints6.ipadx = 2;
			gridBagConstraints6.ipady = 2;
			gridBagConstraints6.gridx = 1;
			GridBagConstraints gridBagConstraints5 = new GridBagConstraints();
			gridBagConstraints5.fill = GridBagConstraints.BOTH;
			gridBagConstraints5.gridy = 2;
			gridBagConstraints5.weightx = 1.0;
			gridBagConstraints5.ipadx = 2;
			gridBagConstraints5.ipady = 2;
			gridBagConstraints5.gridx = 1;
			GridBagConstraints gridBagConstraints4 = new GridBagConstraints();
			gridBagConstraints4.fill = GridBagConstraints.BOTH;
			gridBagConstraints4.gridy = 0;
			gridBagConstraints4.weightx = 1.0;
			gridBagConstraints4.ipadx = 2;
			gridBagConstraints4.ipady = 2;
			gridBagConstraints4.gridx = 1;
			GridBagConstraints gridBagConstraints3 = new GridBagConstraints();
			gridBagConstraints3.gridx = 0;
			gridBagConstraints3.anchor = GridBagConstraints.EAST;
			gridBagConstraints3.ipadx = 2;
			gridBagConstraints3.ipady = 2;
			gridBagConstraints3.gridy = 3;
			GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
			gridBagConstraints2.gridx = 0;
			gridBagConstraints2.anchor = GridBagConstraints.EAST;
			gridBagConstraints2.ipadx = 2;
			gridBagConstraints2.ipady = 2;
			gridBagConstraints2.gridy = 2;
			GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
			gridBagConstraints1.gridx = 0;
			gridBagConstraints1.anchor = GridBagConstraints.EAST;
			gridBagConstraints1.ipadx = 2;
			gridBagConstraints1.ipady = 2;
			gridBagConstraints1.gridy = 1;
			GridBagConstraints gridBagConstraints = new GridBagConstraints();
			gridBagConstraints.fill = GridBagConstraints.BOTH;
			gridBagConstraints.gridy = 1;
			gridBagConstraints.weightx = 1.0;
			gridBagConstraints.ipadx = 2;
			gridBagConstraints.ipady = 2;
			gridBagConstraints.gridx = 1;
			jLabel3 = new JLabel();
			jLabel3.setText("Telefono:");
			jLabel2 = new JLabel();
			jLabel2.setText("Apellido:");
			jLabel1 = new JLabel();
			jLabel1.setText("Nombre:");
			jLabel = new JLabel();
			jLabel.setText("Id:");
			jPanelPersona = new JPanel();
			jPanelPersona.setLayout(new GridBagLayout());
			jPanelPersona.setBorder(BorderFactory.createTitledBorder(
					BorderFactory.createLineBorder(Color.gray, 1), "Persona",
					TitledBorder.DEFAULT_JUSTIFICATION,
					TitledBorder.DEFAULT_POSITION, new Font("Dialog",
							Font.BOLD, 12), new Color(51, 51, 51)));
			jPanelPersona.add(jLabel, gridBagConstraints11);
			jPanelPersona.add(jLabel1, gridBagConstraints1);
			jPanelPersona.add(jLabel2, gridBagConstraints2);
			jPanelPersona.add(jLabel3, gridBagConstraints3);
			jPanelPersona.add(getTfNombre(), gridBagConstraints);
			jPanelPersona.add(getTfId(), gridBagConstraints4);
			jPanelPersona.add(getTfApellido(), gridBagConstraints5);
			jPanelPersona.add(getTfTelefono(), gridBagConstraints6);
		}
		return jPanelPersona;
	}

	/**
	 * This method initializes jPanelDireccion
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJPanelDireccion() {

		if (jPanelDireccion == null) {
            //Label Calle
            GridBagConstraints gridBagConstraints7 = new GridBagConstraints();
            gridBagConstraints7.anchor = GridBagConstraints.EAST;
			gridBagConstraints7.ipady = 2;
			gridBagConstraints7.ipadx = 2;

			
            //TxtCalle
            GridBagConstraints gridBagConstraints8 = new GridBagConstraints();
			gridBagConstraints8.fill = GridBagConstraints.BOTH;
			gridBagConstraints8.gridy = 1;
			gridBagConstraints8.weightx = 1.0;
			gridBagConstraints8.ipadx = 2;
			gridBagConstraints8.ipady = 2;
			gridBagConstraints8.gridx = 1;
            //Lbl Numero

            GridBagConstraints gridBagConstraints9 = new GridBagConstraints();
			gridBagConstraints9.gridx = 0;
			gridBagConstraints9.anchor = GridBagConstraints.EAST;
			gridBagConstraints9.ipadx = 2;
			gridBagConstraints9.ipady = 2;
			gridBagConstraints9.gridy = 1;

            //Txt Numero
            GridBagConstraints gridBagConstraints10 = new GridBagConstraints();
			gridBagConstraints10.fill = GridBagConstraints.BOTH;
			gridBagConstraints10.gridy = 0;
			gridBagConstraints10.weightx = 1.0;
			gridBagConstraints10.ipadx = 2;
			gridBagConstraints10.ipady = 2;
			gridBagConstraints10.gridx = 1;

            //LblPiso

            GridBagConstraints gridBagConstraints11 = new GridBagConstraints();
			gridBagConstraints11.gridx = 0;
			gridBagConstraints11.anchor = GridBagConstraints.EAST;
			gridBagConstraints11.ipadx = 2;
			gridBagConstraints11.ipady = 2;
			gridBagConstraints11.gridy = 2;

            //TxtPiso
            GridBagConstraints gridBagConstraints12 = new GridBagConstraints();
			gridBagConstraints12.fill = GridBagConstraints.BOTH;
			gridBagConstraints12.gridy = 2;
			gridBagConstraints12.weightx = 1.0;
			gridBagConstraints12.ipadx = 2;
			gridBagConstraints12.ipady = 2;
			gridBagConstraints12.gridx = 1;

            //Lbl Departamento

             GridBagConstraints gridBagConstraints13 = new GridBagConstraints();
			gridBagConstraints13.gridx = 0;
			gridBagConstraints13.anchor = GridBagConstraints.EAST;
			gridBagConstraints13.ipadx = 2;
			gridBagConstraints13.ipady = 2;
			gridBagConstraints13.gridy = 3;

            //txtDepartamento
            
           GridBagConstraints gridBagConstraints14 = new GridBagConstraints();
			gridBagConstraints14.fill = GridBagConstraints.BOTH;
			gridBagConstraints14.gridy = 3;
			gridBagConstraints14.weightx = 1.0;
			gridBagConstraints14.ipadx = 2;
			gridBagConstraints14.ipady = 2;
			gridBagConstraints14.gridx = 1;

            jLabelCalle = new JLabel();
			jLabelCalle.setText("Calle:");
            jLabelNumero = new JLabel();
			jLabelNumero.setText("Numero");
            jLabelPiso = new JLabel();
			jLabelPiso.setText("Piso");

            jLabelDepartamento = new JLabel();
			jLabelDepartamento.setText("Departamento");
					
			jPanelDireccion = new JPanel();
			jPanelDireccion.setLayout(new GridBagLayout());
			jPanelDireccion.setBorder(BorderFactory.createTitledBorder(
					BorderFactory.createLineBorder(Color.gray, 1), "Direccion",
					TitledBorder.DEFAULT_JUSTIFICATION,
					TitledBorder.DEFAULT_POSITION, new Font("Dialog",
							Font.BOLD, 12), new Color(51, 51, 51)));

			jPanelDireccion.add(jLabelCalle, gridBagConstraints7);
            jPanelDireccion.add(jLabelNumero, gridBagConstraints9);
            jPanelDireccion.add(jLabelPiso, gridBagConstraints11);
            jPanelDireccion.add(jLabelDepartamento, gridBagConstraints13);

            jPanelDireccion.add(getTfCalle(), gridBagConstraints8);
            jPanelDireccion.add(getTfNumero(), gridBagConstraints10);
			jPanelDireccion.add(getTfPiso(), gridBagConstraints12);
            jPanelDireccion.add(getTfDepartamento(), gridBagConstraints14);
		}
		return jPanelDireccion;
	}

    /**
	 * This method initializes jTextField1
	 *
	 * @return javax.swing.JTextField
	 */
	private JTextField getTfId() {
		if (tfId == null) {
			tfId = new JTextField();
		}
		return tfId;
	}

	/**
	 * This method initializes tfNombre
	 * 
	 * @return javax.swing.JTextField
	 */
	private JTextField getTfNombre() {
		if (tfNombre == null) {
			tfNombre = new JTextField();
		}
		return tfNombre;
	}

	

	/**
	 * This method initializes tfApellido
	 * 
	 * @return javax.swing.JTextField
	 */
	private JTextField getTfApellido() {
		if (tfApellido == null) {
			tfApellido = new JTextField();
		}
		return tfApellido;
	}

	/**
	 * This method initializes tfFechaNacimiento
	 * 
	 * @return javax.swing.JTextField
	 */
	private JTextField getTfTelefono() {
		if (tfTelefono == null) {
			tfTelefono = new JTextField();
		}
		return tfTelefono;
	}

	/**
	 * This method initializes tfCalle
	 * 
	 * @return javax.swing.JTextField
	 */
	private JTextField getTfCalle() {
		if (tfCalle == null) {
			tfCalle = new JTextField();
		}
		return tfCalle;
	}

    /**
	 * This method initializes tfCalle
	 *
	 * @return javax.swing.JTextField
	 */
	private JTextField getTfNumero() {
		if (tfNumero == null) {
			tfNumero = new JTextField();
		}
		return tfNumero;
	}


	/**
	 * This method initializes tfCiudad
	 * 
	 * @return javax.swing.JTextField
	 */
	private JTextField getTfPiso() {
		if (tfPiso == null) {
			tfPiso = new JTextField();
		}
		return tfPiso;
	}

	/**
	 * This method initializes tfCodigoPostal
	 * 
	 * @return javax.swing.JTextField
	 */
	private JTextField getTfDepartamento() {
		if (tfDepartamento == null) {
			tfDepartamento = new JTextField();
		}
		return tfDepartamento;
	}

	/**
	 * This method initializes jPanel1	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanelListado() {
		if (jPanelListado == null) {
			jPanelListado = new JPanel();
			jPanelListado.setLayout(new BorderLayout());
			jPanelListado.add(getJScrollPane(), BorderLayout.CENTER);
		}
		return jPanelListado;
	}

	/**
	 * This method initializes jScrollPane	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getJScrollPane() {
		if (jScrollPane == null) {
			jScrollPane = new JScrollPane();
			jScrollPane.setViewportView(getJTable());
		}
		return jScrollPane;
	}

	/**
	 * This method initializes jTable	
	 * 	
	 * @return javax.swing.JTable	
	 */
	private JTable getJTable() {
		if (jTable == null) {
			jTable = new JTable();
		}
		return jTable;
	}

	/**
	 * @param args
	 * @throws UnsupportedLookAndFeelException 
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 * @throws ClassNotFoundException 
	 */
	
    public static void main(String[] args) throws Exception {
		UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		SwingUtilities.invokeLater(new Runnable() {
            @Override
			public void run() {
				VisualUI thisClass = new VisualUI();
				thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				thisClass.setVisible(true);
			}
		}
        );
	}

    /**
	 * This is the default constructor
	 */
	public VisualUI() {
		super();
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setContentPane(getJContentPane());
		this.setTitle("Administracion Jugador");
		this.setSize(new Dimension(250, 297));
		this.pack();
		// Inicializa el servicios
		altaService = new PersonaServicio();
		altaService.init(this);
		listadoService = (IListadoPersonaServicio) altaService;

		// llena la tabla

        llenarTablaPersonas();
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(new BorderLayout());
			jContentPane.add(getJTabbedPane(), BorderLayout.CENTER);
		}
		return jContentPane;
	}

	/*
	 * Modelo mediante el cual se carga la tabla 
	 */
	private class PersonasModel extends AbstractTableModel {
		
		private static final long serialVersionUID = 4398627101885762332L;
		protected Object[][] contents;
        private String[] columnNames = {"Id","Nombre","Apellido", "Telefono","Calle","Numero","Piso","Departamento"};
		
		public PersonasModel(List<Persona> data) {
			List<Object[]> fila = new ArrayList<Object[]>();
			for (Persona p : data) {
				List<String> celda = new ArrayList<String>();
				celda.add("" + p.getId());
				celda.add(p.getNombre());
				celda.add(p.getApellido());
                celda.add(p.getTelefono());
                celda.add(p.getDireccionParticular().getCalle());
                celda.add(String.valueOf(p.getDireccionParticular().getNumero()));
                celda.add(p.getDireccionParticular().getPiso());
                celda.add(p.getDireccionParticular().getDepartamento());
               	fila.add(celda.toArray());
			}
            contents = new Object[fila.size()][];
            for (int i = 0; i < contents.length; i++) {
                contents[i] = (Object[]) fila.get(i);
            }
		}
		
		@Override
		public int getColumnCount() {
            if (contents.length == 0) {
                return 0;
            } else {
                return contents[0].length;
            }
		}

		@Override
		public int getRowCount() {
			return contents.length;
		}

		@Override
		public Object getValueAt(int rowIndex, int columnIndex) {
			return contents[rowIndex][columnIndex];
		}
		
		@Override
        public String getColumnName(int column) {
            return columnNames[column];
        }

	}
} // @jve:decl-index=0:visual-constraint="10,10"
